<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Reality | Reality</title><meta name="keywords" content="Java, 全栈"><meta name="author" content="dtyy"><meta name="copyright" content="dtyy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="1 Nginx配置负载均衡1.1 配置反向代理&#x2F;负载均衡配置反向代理：配置一个server虚拟主机(server 块) 用来监听端口，用来接收http请求，location 配置为 proxy_pass(代理通过) 用来表示请求转发到上游服务器 upstream。 配置多台server，便具有了负载均衡。 upstream cluster （upstream 块）上有服务器信息，内部包含{ sev">
<meta property="og:type" content="article">
<meta property="og:title" content="Reality">
<meta property="og:url" content="https://dtyytop.gitee.io/2021/05/13/devnotes/ji-qun-yan-jin/nginx/2.3-nginx-fu-zai-jun-heng-suan-fa-yu-pei-zhi/index.html">
<meta property="og:site_name" content="Reality">
<meta property="og:description" content="1 Nginx配置负载均衡1.1 配置反向代理&#x2F;负载均衡配置反向代理：配置一个server虚拟主机(server 块) 用来监听端口，用来接收http请求，location 配置为 proxy_pass(代理通过) 用来表示请求转发到上游服务器 upstream。 配置多台server，便具有了负载均衡。 upstream cluster （upstream 块）上有服务器信息，内部包含{ sev">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg">
<meta property="article:published_time" content="2021-05-13T14:22:22.349Z">
<meta property="article:modified_time" content="2021-05-13T14:22:22.349Z">
<meta property="article:author" content="dtyy">
<meta property="article:tag" content="Java, 全栈">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://dtyytop.gitee.io/2021/05/13/devnotes/ji-qun-yan-jin/nginx/2.3-nginx-fu-zai-jun-heng-suan-fa-yu-pei-zhi/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"prismjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: dtyy","link":"链接: ","source":"来源: Reality","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Reality',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-05-13 22:22:22'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Reality" type="application/atom+xml">

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Reality</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">无题</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-05-13T14:22:22.349Z" title="发表于 2021-05-13 22:22:22">2021-05-13</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-05-13T14:22:22.349Z" title="更新于 2021-05-13 22:22:22">2021-05-13</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="1-Nginx配置负载均衡"><a href="#1-Nginx配置负载均衡" class="headerlink" title="1 Nginx配置负载均衡"></a>1 Nginx配置负载均衡</h2><h3 id="1-1-配置反向代理-负载均衡"><a href="#1-1-配置反向代理-负载均衡" class="headerlink" title="1.1 配置反向代理/负载均衡"></a>1.1 配置反向代理/负载均衡</h3><p>配置反向代理：配置一个server虚拟主机(server 块) 用来监听端口，用来接收http请求，location 配置为 proxy_pass(代理通过) 用来表示请求转发到上游服务器 upstream。</p>
<p>配置多台server，便具有了负载均衡。</p>
<p>upstream cluster （upstream 块）上有服务器信息，内部包含{ sever 服务器ip对应端口} ，如果是多台会自动实现负载均衡。</p>
<pre class="line-numbers language-nginx" data-language="nginx"><code class="language-nginx"><span class="token comment"># 配置上游服务器（测试时在一台虚拟机上配置了两台Tomcat）</span>
<span class="token keyword">upstream</span> cluster <span class="token punctuation">{</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8080</span><span class="token punctuation">;</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8088</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment"># 配置server</span>
<span class="token keyword">server</span> <span class="token punctuation">{</span>
    <span class="token keyword">listen</span>      <span class="token number">80</span><span class="token punctuation">;</span>
    <span class="token keyword">server_name</span>     www<span class="token punctuation">.</span>awecoder<span class="token punctuation">.</span>com<span class="token punctuation">;</span>
    
    <span class="token keyword">location</span> <span class="token operator">/</span> <span class="token punctuation">{</span>
        <span class="token comment"># 转发请求</span>
        <span class="token keyword">proxy_pass</span>  <span class="token keyword">http</span><span class="token punctuation">:</span><span class="token operator">/</span><span class="token operator">/</span>cluster<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="1-2-Jmeter压力测试"><a href="#1-2-Jmeter压力测试" class="headerlink" title="1.2 Jmeter压力测试"></a>1.2 Jmeter压力测试</h3><p>Jmeter官网jmeter.apache.org下载并按照压测工具。<br>使用步骤：</p>
<ol>
<li>添加线程组–配置线程数、间隔、每个线程发送多少请求</li>
<li>添加取样器–HTTP请求–添加ip/端口等</li>
<li>添加监听器–聚合报告/结果数/表格查看结果。</li>
</ol>
<p>注意关注异常率，查看请求成功与失败的日志。可以设置异常率阈值（例如20%），超过阈值表示到达并发峰值，需要进行扩容等操作。</p>
<p>针对于上面配置负载均衡的压力测试，首先直接访问某个Tomcat服务器，再测试访问Nginx集群，查看压测效果。</p>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/4558_1.png" alt="4558_1"></p>
<p>注：本地测试，可能会出现集群错误率高于单机的情况。本地压测有大量IO，nginx作为中转代理，所有请求流量会经过nginx分发，对网络和磁盘都有要求。</p>
<h3 id="1-3-upstream-模块参数"><a href="#1-3-upstream-模块参数" class="headerlink" title="1.3 upstream 模块参数"></a>1.3 upstream 模块参数</h3><ol>
<li>weight 节点资源不均时，设置权重</li>
<li> max_conns 限制每台上游服务器最大的连接数，防止过载，起到限流作用。请求超出阈值，会异常502：Bad Gateway。<pre class="line-numbers language-nginx" data-language="nginx"><code class="language-nginx"><span class="token keyword">upstream</span> cluster <span class="token punctuation">{</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8080</span> max_conns<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">;</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8088</span> max_conns<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre></li>
<li>slow_start 缓启动，服务器从0逐渐升至设定值。是付费功能，不能用于hash和random负载均衡方法；只有一台服务器时，参数失效。<pre class="line-numbers language-none"><code class="language-none">server 192.168.233.130:8088 weight=3 slow_start=30s;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre></li>
<li>down 标记某个节点（server）永久不可用。</li>
<li>backup 标记节点为备用机，在主节点全部宕机时才会启用。不能用于hash和random负载均衡方法。</li>
<li>max_fails 和 fail_timeout 结合使用。max_fails 表示失败几次，则标记该server已宕机。fail_timeout 表示重试时间。默认1次，10s。</li>
</ol>
<p>max_fails=3 fail_timeout=30s 代表在30s内请求某个节点失败3次，认为该节点宕机，然后等待30s，期间内新的请求值发送给正常的应用。直到30s后，Nginx再次尝试转发新请求到宕机节点，并且仅尝试一次，如果还是失败，则继续等待30s，直到节点恢复。</p>
<h3 id="1-4-http-upstream-模块参数"><a href="#1-4-http-upstream-模块参数" class="headerlink" title="1.4 http upstream 模块参数"></a>1.4 http upstream 模块参数</h3><ol>
<li>keepalive connections 缓存上游节点的连接，我们可以视为长连接。缓存长连接，可以提高吞吐量。<pre class="line-numbers language-nginx" data-language="nginx"><code class="language-nginx"><span class="token keyword">upstream</span> cluster <span class="token punctuation">{</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8080</span><span class="token punctuation">;</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8088</span><span class="token punctuation">;</span>

    <span class="token keyword">keepalive</span> <span class="token number">32</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">server</span> <span class="token punctuation">{</span>
    <span class="token keyword">listen</span>      <span class="token number">80</span><span class="token punctuation">;</span>
    <span class="token keyword">server_name</span>     www<span class="token punctuation">.</span>awecoder<span class="token punctuation">.</span>com<span class="token punctuation">;</span>

    <span class="token keyword">location</span> <span class="token operator">/</span> <span class="token punctuation">{</span>
        <span class="token keyword">proxy_pass</span>  <span class="token keyword">http</span><span class="token punctuation">:</span><span class="token operator">/</span><span class="token operator">/</span>cluster<span class="token punctuation">;</span>

        <span class="token comment"># HTTP 1.1 才支持长连接，并清空连接头</span>
        <span class="token keyword">proxy_http_version</span> <span class="token number">1.1</span><span class="token punctuation">;</span>
        <span class="token keyword">proxy_set_header</span> Connection <span class="token string">""</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
</ol>
<h2 id="2-负载均衡算法"><a href="#2-负载均衡算法" class="headerlink" title="2 负载均衡算法"></a>2 负载均衡算法</h2><h3 id="2-1-轮询（RR）与加权轮询（WRR，使用较多）"><a href="#2-1-轮询（RR）与加权轮询（WRR，使用较多）" class="headerlink" title="2.1 轮询（RR）与加权轮询（WRR，使用较多）"></a>2.1 轮询（RR）与加权轮询（WRR，使用较多）</h3><p>Nginx默认的负载均衡策略是轮询，每个节点接收几乎同样数量的请求。<br>服务器配置通常不同，硬件配置越好，处理的请求也会越多。可以配置节点权重，改变nginx请求转发比例。</p>
<pre class="line-numbers language-nginx" data-language="nginx"><code class="language-nginx"><span class="token keyword">upstream</span> cluster <span class="token punctuation">{</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8080</span> weight<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8088</span> weight<span class="token operator">=</span><span class="token number">3</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>weight=1是默认权重，weight值越高，服务器接收请求几率越大。</p>
<h3 id="2-2-ip-hash算法"><a href="#2-2-ip-hash算法" class="headerlink" title="2.2 ip_hash算法"></a>2.2 ip_hash算法</h3><p>通过ip_hash算法，可以保证对于同一个ip，hash值相同，即同一个请求可以访问同一个节点。</p>
<p>hash(ip) % node_counts = index</p>
<p>类似场景，例如数据库分表，假设将某张表拆分成三张表，可以将主键取出取hash和取模，放入分表中。</p>
<pre class="line-numbers language-nginx" data-language="nginx"><code class="language-nginx"><span class="token keyword">upstream</span> cluster <span class="token punctuation">{</span>
    <span class="token keyword">ip_hash</span><span class="token punctuation">;</span>
    
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8080</span><span class="token punctuation">;</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8088</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>使用ip_hash需要注意的是，</p>
<ol>
<li>如果采用动态ip，则不能保证每次访问到相同节点。</li>
<li>如果用户发起高并发请求，或者恶意请求，会导致某个节点性能急剧下降。</li>
<li>如果某个server需要临时删除，需要使用down参数标记，以此保留客户端ip地址的当前hash值。如果直接删除，所有hash取模需要重新计算，用户会话丢失，缓存失效。</li>
</ol>
<h3 id="2-3-其他算法（least-conn-url-hash-fair）"><a href="#2-3-其他算法（least-conn-url-hash-fair）" class="headerlink" title="2.3 其他算法（least_conn/url_hash/fair）"></a>2.3 其他算法（least_conn/url_hash/fair）</h3><ul>
<li>url_hash算法 （第三方） 根据每次请求的url地址，hash后访问到固定的服务器节点。当然，节点也可以是一台Nginx。</li>
<li>least_conn 传入的请求是根据每台服务器当前所打开的连接数来分配。</li>
<li>fair（第三方）根据后台响应时间来分发请求，响应时间短的分发的请求多。<pre class="line-numbers language-nginx" data-language="nginx"><code class="language-nginx"><span class="token keyword">upstream</span> cluster <span class="token punctuation">{</span>
    hash <span class="token variable">$request_uri</span><span class="token punctuation">;</span>
    <span class="token comment">#least_conn</span>
    
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8080</span><span class="token punctuation">;</span>
    <span class="token keyword">server</span> <span class="token number">192.168</span><span class="token number">.233</span><span class="token number">.130</span><span class="token punctuation">:</span><span class="token number">8088</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="2-4-一致性哈希算法-（需要引入第三方模块ngx-http-upstream-consistent-hash，了解原理）"><a href="#2-4-一致性哈希算法-（需要引入第三方模块ngx-http-upstream-consistent-hash，了解原理）" class="headerlink" title="2.4 一致性哈希算法 （需要引入第三方模块ngx_http_upstream_consistent_hash，了解原理）"></a>2.4 一致性哈希算法 （需要引入第三方模块ngx_http_upstream_consistent_hash，了解原理）</h3>一致性hash算法提出的初衷是为了解决分布式缓存问题，在分布式系统中广泛应用。</li>
</ul>
<p><strong>考虑到分布式系统每个节点都有可能失效，并且新的节点很可能动态的增加进来，如何保证当系统的节点数目发生变化时仍然能够对外提供良好的服务</strong>，这是值得考虑的。尤其是在设计分布式缓存系统时，如果某台服务器失效，对于整个系统来说如果不采用合适的算法来保证一致性，那么缓存于系统中的所有数据都可能会失效（因为节点总数减少，客户端请求经过hash取模时，hash值发生改变，很可能找不到原先保存该对象的节点），因此一致性hash就显得至关重要。</p>
<h4 id="一致性hash算法原理"><a href="#一致性hash算法原理" class="headerlink" title="一致性hash算法原理"></a>一致性hash算法原理</h4><ol>
<li>一致性哈希将整个哈希值空间组织成一个虚拟的圆环，如假设某哈希函数H的值空间为0-2^32-1（即哈希值是一个32位无符号整形），整个哈希空间环如下：</li>
</ol>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/4572_1.png" alt="4572_1"></p>
<p>整个空间按顺时针方向组织。0和2^32-1在零点中方向重合。　　</p>
<ol start="2">
<li><p>将各个服务器使用Hash进行一个哈希，具体可以选择服务器的ip或主机名作为关键字进行哈希，这样每台机器就能确定其在哈希环上的位置。</p>
</li>
<li><p>使用如下算法定位数据访问到相应服务器：将数据key使用相同的函数Hash计算出哈希值，并确定此数据在环上的位置，从此位置沿环顺时针“行走”，第一台遇到的服务器就是其应该定位到的服务器。　　<br>例如我们有Object A、Object B、Object C、Object D四个数据对象，经过哈希计算后，在环空间上的位置如下：</p>
</li>
</ol>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/4574_1.png" alt="4574_1"></p>
<ol start="4">
<li><p>容错性分析。现假设Node C不幸宕机，可以看到此时对象A、B、D不会受到影响，只有C对象被重定位到Node D。一般的，在一致性哈希算法中，如果一台服务器不可用，则受影响的数据仅仅是此服务器到其环空间中前一台服务器（即沿着逆时针方向行走遇到的第一台服务器）之间数据，其它不会受到影响。</p>
</li>
<li><p>可扩展性分析。<br>下面考虑另外一种情况，如果在系统中增加一台服务器Node X，此时对象Object A、B、D不受影响，只有对象C需要重定位到新的Node X 。</p>
</li>
</ol>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/4576_1.png" alt="4576_1"></p>
<ol start="6">
<li>对于服务节点过少，造成数据倾斜问题，一致性hash算法采用虚拟节点机制。</li>
</ol>
<h4 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h4><p>一致性hash算法有着这样几个特点：</p>
<ol>
<li>hash结果在空间内尽量均匀（hash算法的共性）。</li>
<li>具有良好的容错性和扩展性，在节点宕机和扩展节点时，影响最少的数据。</li>
</ol>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><ul>
<li><a target="_blank" rel="noopener" href="https://www.cnblogs.com/williamjie/p/9477852.html">https://www.cnblogs.com/williamjie/p/9477852.html</a> 一致性hash博客</li>
<li>官方文档：<a target="_blank" rel="noopener" href="http://nginx.org/en/docs/">http://nginx.org/en/docs/</a></li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">dtyy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://dtyytop.gitee.io/2021/05/13/devnotes/ji-qun-yan-jin/nginx/2.3-nginx-fu-zai-jun-heng-suan-fa-yu-pei-zhi/">https://dtyytop.gitee.io/2021/05/13/devnotes/ji-qun-yan-jin/nginx/2.3-nginx-fu-zai-jun-heng-suan-fa-yu-pei-zhi/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://dtyytop.gitee.io" target="_blank">Reality</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/05/13/devnotes/ji-qun-yan-jin/nginx/1.5-nginx-chang-yong-pei-zhi/"><img class="prev-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222634.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info"></div></div></a></div><div class="next-post pull-right"><a href="/2021/05/13/devnotes/ji-qun-yan-jin/nginx/2.4-nginx-huan-cun-jie-jue-fang-an/"><img class="next-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info"></div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">dtyy</div><div class="author-info__description">Java全栈</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/dtyytop"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/dtyytop" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1607961042@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-Nginx%E9%85%8D%E7%BD%AE%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1"><span class="toc-number">1.</span> <span class="toc-text">1 Nginx配置负载均衡</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E9%85%8D%E7%BD%AE%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86-%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1"><span class="toc-number">1.1.</span> <span class="toc-text">1.1 配置反向代理&#x2F;负载均衡</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-Jmeter%E5%8E%8B%E5%8A%9B%E6%B5%8B%E8%AF%95"><span class="toc-number">1.2.</span> <span class="toc-text">1.2 Jmeter压力测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-upstream-%E6%A8%A1%E5%9D%97%E5%8F%82%E6%95%B0"><span class="toc-number">1.3.</span> <span class="toc-text">1.3 upstream 模块参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-4-http-upstream-%E6%A8%A1%E5%9D%97%E5%8F%82%E6%95%B0"><span class="toc-number">1.4.</span> <span class="toc-text">1.4 http upstream 模块参数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AE%97%E6%B3%95"><span class="toc-number">2.</span> <span class="toc-text">2 负载均衡算法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E8%BD%AE%E8%AF%A2%EF%BC%88RR%EF%BC%89%E4%B8%8E%E5%8A%A0%E6%9D%83%E8%BD%AE%E8%AF%A2%EF%BC%88WRR%EF%BC%8C%E4%BD%BF%E7%94%A8%E8%BE%83%E5%A4%9A%EF%BC%89"><span class="toc-number">2.1.</span> <span class="toc-text">2.1 轮询（RR）与加权轮询（WRR，使用较多）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-ip-hash%E7%AE%97%E6%B3%95"><span class="toc-number">2.2.</span> <span class="toc-text">2.2 ip_hash算法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E5%85%B6%E4%BB%96%E7%AE%97%E6%B3%95%EF%BC%88least-conn-url-hash-fair%EF%BC%89"><span class="toc-number">2.3.</span> <span class="toc-text">2.3 其他算法（least_conn&#x2F;url_hash&#x2F;fair）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E4%B8%80%E8%87%B4%E6%80%A7%E5%93%88%E5%B8%8C%E7%AE%97%E6%B3%95-%EF%BC%88%E9%9C%80%E8%A6%81%E5%BC%95%E5%85%A5%E7%AC%AC%E4%B8%89%E6%96%B9%E6%A8%A1%E5%9D%97ngx-http-upstream-consistent-hash%EF%BC%8C%E4%BA%86%E8%A7%A3%E5%8E%9F%E7%90%86%EF%BC%89"><span class="toc-number">2.4.</span> <span class="toc-text">2.4 一致性哈希算法 （需要引入第三方模块ngx_http_upstream_consistent_hash，了解原理）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%80%E8%87%B4%E6%80%A7hash%E7%AE%97%E6%B3%95%E5%8E%9F%E7%90%86"><span class="toc-number">2.4.1.</span> <span class="toc-text">一致性hash算法原理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-number">2.4.2.</span> <span class="toc-text">小结</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="toc-number">3.</span> <span class="toc-text">参考资料</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222600.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx进程模型"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型">Nginx进程模型</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx核心配置结构"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构">Nginx核心配置结构</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="集群、代理与Nginx"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx">集群、代理与Nginx</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222646.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis主从复制架构与原理"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理">Redis主从复制架构与原理</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222634.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis的两种持久化机制"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制">Redis的两种持久化机制</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By dtyy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>